package com.cloudinnov.logic.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.stringtemplate.v4.compiler.CodeGenerator.list_return;

import com.cloudinnov.dao.AlarmLogDao;
import com.cloudinnov.dao.ControlSolutionConfigDao;
import com.cloudinnov.dao.ControlSolutionDao;
import com.cloudinnov.dao.EquipmentsDao;
import com.cloudinnov.logic.AlarmLogLogic;
import com.cloudinnov.logic.ControlSolutionLogic;
import com.cloudinnov.model.AlarmLog;
import com.cloudinnov.model.BoardSolutionConfig;
import com.cloudinnov.model.ControlSolutionConfig;
import com.cloudinnov.model.ControlSolutionExpre;
import com.cloudinnov.model.ControlSolutionExpression;
import com.cloudinnov.model.Equipments;
import com.cloudinnov.model.PageModel;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.support.spring.SpringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class AlarmLogLogicImpl extends BaseLogicImpl<AlarmLog> implements AlarmLogLogic {

	@Autowired
	private AlarmLogDao alarmLogDao;
	@Autowired
	private EquipmentsDao equipmentsDao;
	@Autowired
	private ControlSolutionConfigDao controlSolutionConfigDao;
	@Autowired
	private ControlSolutionLogic controlSolutionLogic;
	@Autowired
	private ControlSolutionDao controlSolutionDao;
	JedisPool jedisPool = SpringUtils.getBean("jedisPool");
	
	public Page<AlarmLog> search(PageModel page, AlarmLog model) {
		PageHelper.startPage(page.getIndex(), page.getSize());
		
		Map<String, Object> params = new HashMap<>();
		params.put("language", model.getLanguage());
		params.put("keyword", model.getKey());
		params.put("country", model.getCountry());
		params.put("province", model.getProvince());
		params.put("city", model.getCity());
		params.put("level", model.getLevel());
		params.put("type", model.getType());
		if(CommonUtils.isNotEmpty(model.getEquipmentCode())){
			params.put("equipmentCode", model.getEquipmentCode().split(CommonUtils.SPLIT_COMMA));
		}
		
		return alarmLogDao.search(params);
	}
	
	@Override
	public Page<AlarmLog> selectAlarm(Integer size, Integer index, AlarmLog model) {
		
		PageHelper.startPage(index, size);
		
		Map<String, Object> params = new HashMap<>();
		params.put("language", model.getLanguage());
		params.put("keyword", model.getKey());
		params.put("country", model.getCountry());
		params.put("province", model.getProvince());
		params.put("city", model.getCity());
		params.put("level", model.getLevel());
		params.put("type", model.getType());
		params.put("comCode", model.getCustomerCode());
		if(CommonUtils.isNotEmpty(model.getEquipmentCode())){
			params.put("equipmentCode", model.getEquipmentCode().split(CommonUtils.SPLIT_COMMA));
		}
		
		return alarmLogDao.selectAlarm(params);
	}
	
	@Override
	public Page<AlarmLog> selectFireAlarmListPage(Integer size, Integer index) {
		PageHelper.startPage(index, size);
		Jedis redis = jedisPool.getResource();
		Page<AlarmLog> alarmLog = alarmLogDao.selectLatestFireListPage();
		for(AlarmLog alarm:alarmLog) {
			//控制了哪些设备
			ControlSolutionConfig model = new ControlSolutionConfig();
			model.setSolutionCode(alarm.getSolutionCode());
			List<ControlSolutionConfig> controlSolutionConfigs = controlSolutionConfigDao.selectListBySolutionCode(model);
			String listName = "";
			boolean isFirst = true;
			for(int i=0; i<controlSolutionConfigs.size();i++) {
				if(controlSolutionConfigs.get(i).getIsRecover()==0) {//触发
					String name = controlSolutionConfigs.get(i).getName();
					if(isFirst==true) {
						listName = name;
						isFirst = false;
					} else {
						listName = listName + "、" + name;
					}	
				}
			}
			alarm.setTriggerEquipNames(listName);
			long timestamp = Long.parseLong(alarm.getCreateTime());
			Date date = new Date(timestamp);
			DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
			String dateFormatted = formatter.format(date);
			ControlSolutionExpre controlSolutionExpression = controlSolutionLogic.selectControlSolutionExpreByRecover(alarm.getSolutionCode(), 0);
			String triggerConditions = generateTriggerCondition(controlSolutionExpression, redis, dateFormatted);
			alarm.setTriggerConditions(triggerConditions);
			String pileNos = generatePileNo(controlSolutionExpression);
			alarm.setTriggerEquipPiles(pileNos);
			
		}
		
		return alarmLog;
	}
	
	@Override
	public List<AlarmLog> selectFireAlarmList() {
		Jedis redis = jedisPool.getResource();
		//查询所有alarmLog的记录
		List<AlarmLog> alarmLog = alarmLogDao.selectLatestFireList();
		for(AlarmLog alarm:alarmLog) {
			//控制了哪些设备
			ControlSolutionConfig model = new ControlSolutionConfig();
			model.setSolutionCode(alarm.getSolutionCode());
			List<ControlSolutionConfig> controlSolutionConfigs = controlSolutionConfigDao.selectListBySolutionCode(model);
			String listName = "";
			boolean isFirst = true;
			for(int i=0; i<controlSolutionConfigs.size();i++) {
				if(controlSolutionConfigs.get(i).getIsRecover()==0) {//触发
					String name = controlSolutionConfigs.get(i).getName();
					if(isFirst==true) {
						listName = name;
						isFirst = false;
					} else {
						listName = listName + "、" + name;
					}	
				}
			}
			alarm.setTriggerEquipNames(listName);
			long timestamp = Long.parseLong(alarm.getCreateTime());
			Date date = new Date(timestamp);
			DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
			String dateFormatted = formatter.format(date);
			ControlSolutionExpre controlSolutionExpression = controlSolutionLogic.selectControlSolutionExpreByRecover(alarm.getSolutionCode(), 0);
			String names = controlSolutionExpression.getName();
			if(names != null) {
				if(names.contains("感温光纤") || names.contains("手报")) {
					alarm.setTriggerType("按报警设备触发");
				} else {
					alarm.setTriggerType("按阀值触发");
				}
			}
			String triggerConditions = generateTriggerCondition(controlSolutionExpression, redis, dateFormatted);
			alarm.setTriggerConditions(triggerConditions);
			String pileNos = generatePileNo(controlSolutionExpression);
			alarm.setTriggerEquipPiles(pileNos);
		}
		return alarmLog;
	}
	
	public String generateTriggerCondition(ControlSolutionExpre controlSolutionExpression, Jedis redis, String dateFormatted) {
		Map<String, String> mapValue = new HashMap<String, String>();
		boolean result = false;
		String conditions = controlSolutionExpression.getCondition();
		//获取调接口用的code值,ControlSolutionExpre的code值
		String code = controlSolutionExpression.getCode();
		String pointCode = null;
		//对conditions表达式进行处理
		conditions = conditions.replaceAll("==", "=");
		conditions = conditions.replaceAll("&&", ",");
		conditions = conditions.replaceAll("\\|", ",");
		conditions = conditions.replaceAll("\\(", ",");
		conditions = conditions.replaceAll("\\)", ",");
		//去除多个','号存在的情况,只剩下一个
		while (conditions.contains(",,")) {
			conditions = conditions.replaceAll(",,", ",");
		}
		//去除掉条件中以','开始或以','结尾
		if (conditions.startsWith(",")) {
			conditions = conditions.substring(1);
		}
		if (conditions.endsWith(",")) {
			conditions = conditions.substring(0,conditions.lastIndexOf(","));
		}
		String[] conditionArray = conditions.split(",");
		String[] points = controlSolutionExpression.getPointCode().split(",");
		String[] pointNames = controlSolutionExpression.getName().split(",");
		int pointIndex = 0;
		String prefix = "";
		String singleCondition = "";
		String conditionExpression = "";
		for (String condition : conditionArray) {
			
			String detectorValue = null;
			//pointCode = condition.substring(condition.indexOf("$")+1, condition.indexOf("$")+1+8);
			pointCode = points[pointIndex];
			singleCondition = condition.substring(condition.indexOf("$")+1, condition.length());
			if (pointCode.equals("datetime")) {
				prefix = "时间:";
				detectorValue = dateFormatted;
			} else {
				prefix = pointNames[pointIndex];
				detectorValue = getRedisValue(pointCode, redis);
			}
			
			//判断点位数据的类型:数字sz(手报之类设备)和模拟mn(no2浓度之类设备)
			ControlSolutionExpre controlSolutionExpre = new ControlSolutionExpre();
			controlSolutionExpre.setPointCode(pointCode);
			controlSolutionExpre = controlSolutionDao.selectSolutionExprePointNameByRecover(controlSolutionExpre);
			//获取point点位的数据类型
			String pointType = controlSolutionExpre.getPointType();
//			String pointLocationName = controlSolutionExpre.getPointLocationName();
			if ("sz".equals(pointType)) {
				singleCondition = "触发";
			}else {
				singleCondition = singleCondition.replace(pointCode, "值超标" + detectorValue + "(");
				singleCondition = singleCondition + ")";
			}
			
			if(pointIndex == 0) {
				conditionExpression = "触发时" + prefix + singleCondition + "; ";
			} else {
				conditionExpression = conditionExpression + " " + prefix + singleCondition + "; ";
			}
			
			/*detectorValue = getRedisValue(pointCode, redis);
			mapValue.put("$" + pointCode, detectorValue);
			String expressionFormat = expressionFormat(condition, mapValue);
			//判断字符串的表达式的值是true还是false
			result = judgeExpressionResult(expressionFormat);
 			*/
			pointIndex ++ ;
		}
		return conditionExpression;
		
		/*String singleCondition = "";
		for (int j = 0; j < points.length; j++) {
			
		}
		
		List<ControlSolutionExpre> points = controlSolutionExpression.getPoints();
		String singleCondition = "";
		String pointCode = "";
		String detectorValue = "";
		String conditionExpression = "";
		boolean isFirst = true;
		String prefix = "";
		for (int j = 0; j < points.size(); j++) {
			singleCondition = points.get(j).getCondition();
			pointCode = points.get(j).getPointCode();
			if (singleCondition.indexOf("&&") != -1) {// 与条件情况
				singleCondition = singleCondition.replace("&&$", "");
				if (pointCode.equals("datetime")) {
					prefix = "时间:";
					detectorValue = dateFormatted;
				} else {
					prefix = points.get(j).getName() + ":";
					detectorValue = getRedisValue(pointCode, redis);
					//singleCondition = singleCondition.replace(pointCode, points.get(j).getName());
				}
				singleCondition = singleCondition.replace(pointCode, detectorValue);
				if(isFirst == true) {
					conditionExpression = "触发时" + prefix + singleCondition;
					isFirst = false;
				} else {
					conditionExpression = conditionExpression + " 且 " + prefix + singleCondition;
				}
			} else if (points.get(j).getCondition().indexOf("||") != -1) {// 或条件情况
				singleCondition = singleCondition.replace("||$", "");
				if (pointCode.equals("datetime")) {
					prefix = "时间:";
					detectorValue = dateFormatted;
				} else {
					prefix = points.get(j).getName() + ":";
					detectorValue = getRedisValue(pointCode, redis);
					//singleCondition = singleCondition.replace(pointCode, points.get(j).getName());
				}
				singleCondition = singleCondition.replace(pointCode, detectorValue);
				if(isFirst == true) {
					conditionExpression = "触发时" + prefix + singleCondition;
					isFirst = false;
				} else {
					conditionExpression = conditionExpression + " 或 " + prefix + singleCondition;
				}
			}
		}
		return conditionExpression;*/
	}
	
	public String generatePileNo(ControlSolutionExpre controlSolutionExpression) {
		String[] points = controlSolutionExpression.getPointCode().split(",");
		String pointCode = "";
		String pileNo = "";
		boolean isFirst = true;
		String pileNos = "";
		for (int j = 0; j < points.length; j++) {
			pointCode = points[j];
			if (pointCode.equals("datetime")) {
				
			} else {
				Equipments equipment = equipmentsDao.selectEquPileNoByPointCode(pointCode);
				if(isFirst == true) {
					pileNos = equipment.getPileNo();
					isFirst = false;
				} else {
					pileNos = pileNos + "、" + equipment.getPileNo();
				}
			}
		}
		return pileNos;
	}
	
	public String getRedisValue(String code, Jedis redis) {
		String key = "point:" + code + ":value";
		String result = redis.lindex(key, 0);
		if (result != null) {
			String[] split = result.split(",");
			return split[1];
		} else {
			return -1 + "";
		}
	}
}
